﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Luminji.Core.Data;
using Luminji.Core.Data;
using Luminji.ExamWeb.Core.Domain;
using Luminji.ExamWeb.Core.Domain.Model;

namespace Luminji.ExamWeb.Infrastructure.DataAccess.Impl.SqlServer
{
    public class SubjectRepository : ISubjectRepository
    {
        private static IList<Subject> _all;
        private static IList<Subject> _tree;

        public IList<Subject> GetSubjectAll()
        {
            if (_all == null)
            {
                _all = fromDB();
            }
            return _all;
        }

        public IList<Subject> GetSubjectThree()
        {
            if (_tree == null)
            {
                _all = fromDB();
                Subject root = new Subject();
                RecusiveSubject(root, null);
                _tree = root.Children;
            }
            return _tree;
        }

        IList<Subject> fromDB()
        {
            using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionString, CommandType.Text, "select * from Subject"))
            {
                return ds.Tables[0].ToList<Subject>();
            }
        }

        void RecusiveSubject(Subject subject, string parentCode)
        {
            var tempList = from p in _all where p.ParentCode == parentCode select p;
            if (tempList.Count() == 0)
            {
                return;
            }
            else
            {
                subject.Children = tempList.ToList();
                foreach (var item in tempList)
                {
                    RecusiveSubject(item, item.SubjectCode);
                }
            }
        }
    }
}
